package com.itheima.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.Role;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class RoleServiceImpl implements RoleService {


    @Autowired
    RoleDao roleDao;

    @Override
    public PageResult findPage(QueryPageBean pageBean) {
        PageHelper.startPage(pageBean.getCurrentPage(),pageBean.getPageSize());
        Page<Role> permissions = roleDao.findByCondition(pageBean.getQueryString());
        return new PageResult(permissions.getTotal(), permissions);
    }


    @Override
    public void add(Role role, Integer[] permissionIds, Integer[] menuIds) {
        Role role1=roleDao.findByname(role.getName());
        if(role1!=null){
            throw new BusinessRuntimeException("角色已经存在,添加失败!!!");
        }
        roleDao.add(role);
        setRelation(role.getId(),permissionIds,menuIds);
    }
    private void setRelation(Integer roleId, Integer[] permissionIds, Integer[] menuIds){
        if(permissionIds != null && permissionIds.length > 0){
            for (Integer permissionId : permissionIds) {
                roleDao.setRelation(roleId, permissionId);
            }
            for (Integer menuId : menuIds) {
                roleDao.setRelation2(roleId,menuId);
            }
        }
    }

    @Override
    public void delById(Integer id) {
        long count = roleDao.findCountById(id);
        long count2 = roleDao.findCountById2(id);
        if(count > 0 || count2 > 0) {
            throw new BusinessRuntimeException("该角色被菜单或者用户关联，不能删除！！");
        }
        roleDao.delRelation(id);
        roleDao.delRelation2(id);
        roleDao.delById(id);
    }

    @Override
    public Role findById(Integer id) {
        return roleDao.findById(id);
    }

    @Override
    public List<Integer> findpermissionIdsByroleId(Integer roleId) {
        return roleDao.findpermissionIdsByroleId(roleId);
    }

    @Override
    @Transactional
    public void edit(Role role, Integer[] permissionIds, Integer[] menuIds) {
        roleDao.delRelation(role.getId());
        roleDao.delRelation2(role.getId());
        setRelation(role.getId(), permissionIds,menuIds);
        roleDao.edit(role);
    }

    @Override
    public List<Integer> findmenuIdsByroleId(Integer roleId) {
        return roleDao.findmenuIdsByroleId(roleId);
    }
}
